package com.lh.java.basic.grammer;

import java.util.Collection;
import java.util.HashSet;

import org.hamcrest.core.IsInstanceOf;

/**
 ************************************************
 ** Module : 两个对象相等，hashcode一定相等
 **       hashcode 相等，两个对象可能不相等
 **(1)当obj1.equals(obj2)为true时，obj1.hashCode() == obj2.hashCode()必须为true
 **(2)当obj1.hashCode() == obj2.hashCode()为false时，obj1.equals(obj2)必须为false
 ** 特别指出利用equals比较八大包装对象（如int，float等）和String类
 **（因为该类已重写了equals和hashcode方法）对象时，默认比较的是值
 ** 在比较其它自定义对象时都是比较的引用地址
 ** Date: 2013-3-21  Time: 上午10:42:21 
 ** Author lh 
 ************************************************ 
 */
public class TestHashCode {
	
	public static void main(String[] args) {
		Name nOne =  new Name();
		Name nTow =  new Name();
		nOne.name="zhangshang";
		nTow.name="zhangshang";
		System.out.println(nOne.equals(nTow));
		System.out.println(nOne.equals(nOne));
		
		 Collection c = new HashSet(); 
		  c.add(nOne);  
	        System.out.println("------------");  
	        c.add(nTow);  
	        System.out.println("------------");  
	        System.out.println(nOne.equals(nTow));  
	        System.out.println("------------");  
	        System.out.println(nOne.hashCode());  
	        System.out.println(nTow.hashCode());  
	        System.out.println(c);  
	}

}
class Name {
	public String name;
	public int age;
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public int hashCode() {		
		return name.hashCode();
	}
	@Override
	public boolean equals(Object obj) {
		if(this==obj){
			return true;
		}
		if(obj instanceof Name){
			if(this.name.equals(((Name) obj).name)){
				return true;
			}
		}
		
		return false;
	}


}
